"use client";
import { useCopilotAction } from "@copilotkit/react-core";
import { CopilotPopup } from "@copilotkit/react-ui";
import { useState, useEffect } from "react";
import { useCopilotChat } from "@copilotkit/react-core";

export default function CopilotComponent() {
  const [isClient, setIsClient] = useState(false);
  const { visibleMessages, isLoading } = useCopilotChat();

  useEffect(() => {
    setIsClient(true);
  }, []);

  useCopilotAction({
    name: "RequestAssistance",
    parameters: [
      {
        name: "request",
        type: "string",
      },
    ],
    renderAndWait: ({ args, status, handler }) => {
      const [response, setResponse] = useState("");
      return (
        <div className="p-4 bg-gray-100 rounded shadow-md">
          <p className="mb-2 text-gray-700">{args.request}</p>
          <div className="flex items-center space-x-2">
            <input
              type="text"
              className="flex-grow p-2 border border-gray-300 rounded max-w-[calc(100%-100px)]"
              placeholder="Your response..."
              value={response}
              onChange={(e) => setResponse(e.target.value)}
            />
            {status === "executing" && (
              <button
                type="button"
                className="px-4 py-2 text-white bg-blue-500 rounded hover:bg-blue-600"
                onClick={() => handler(response)}
              >
                Submit
              </button>
            )}
          </div>
        </div>
      );
    },
  });

  // 只在客户端渲染组件
  if (!isClient) {
    return <div className="flex items-center justify-center h-screen">Loading...</div>;
  }

  // 只在 isLoading 时查找最新的 ActionExecutionMessage
  let toolName: string | undefined;
  if (isLoading) {
    const latestToolMsg = [...visibleMessages].reverse().find(
      (msg: any) => msg.type === "ActionExecutionMessage"
    ) as any;
    toolName = latestToolMsg?.name;
  }

  return (
    <>
      {/* 只在工具调用进行中显示提示 */}
      {isLoading && toolName && (
        <div className="fixed top-4 left-1/2 -translate-x-1/2 z-50 bg-yellow-100 text-yellow-800 px-4 py-2 rounded shadow">
          助手正在调用「{toolName}」工具...
        </div>
      )}
      <CopilotPopup
        instructions={
          "You are assisting the user as best as you can. Answer in the best way possible given the data you have."
        }
        defaultOpen={true}
        labels={{
          title: "Popup Assistant",
          initial: "Need any help?",
        }}
      />
    </>
  );
}
